/*
 * Copyright (C) 2022-2022. Huawei Technologies Co., Ltd. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.openlookeng.core.tool;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

@Slf4j
public class Md5Utils
{
    private static final String key = "wm!";

    private static final String aesKey = "wm12345678QWEASD";

    private static final AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, aesKey.getBytes(), StrUtil.reverse(Md5Utils.aesKey).getBytes());

    private Md5Utils()
    {
    }

    /**
     * @param text
     * @return tomd5
     */
    public static String tomd5(String text) throws Exception
    {
        return DigestUtils.md5Hex(text + key);
    }

    public static String toAes(String text) throws Exception
    {
        return aes.encryptBase64(text);
    }

    public static String decrypt(String pwd)
    {
        String decoder = null;
        try {
            decoder = aes.decryptStr(pwd);
        }
        catch (Exception e) {
            return pwd;
        }
        return decoder;
    }

    /**
     * @param text
     * @param md5
     */
    public static boolean decodeMd5(String text, String md5) throws Exception
    {
        String md5str = tomd5(text);
        if (md5str.equalsIgnoreCase(md5)) {
            return true;
        }
        return false;
    }
}
